package com.mystnihon.loader;

import android.content.Context;
import android.os.AsyncTask;

public abstract class AbstractAsyncLoader<T> {
    protected static final String TAG = AbstractAsyncLoader.class.getSimpleName();

    public interface LoadingListener<T> {
        public void onLoadFinished(T data);

        public void onLoadError(T data, String errorMessage);
    }

    private LoadingListener<T> mLoadingListener;
    protected T mReturnData;
    protected String mErrorMessage;

    public AbstractAsyncLoader() {
        mErrorMessage = "Message not set";
    }

    protected abstract boolean doLoad(Context context);

    public void loadAsync(Context ctx, LoadingListener<T> listener) {
        mLoadingListener = listener;

        new Loader(ctx).execute();
    }

    class Loader extends AsyncTask<Void, Void, Boolean> {

        Context mCtx;

        public Loader(Context ctx) {
            mCtx = ctx;
        }

        @Override
        protected Boolean doInBackground(Void... params) {

            return doLoad(mCtx);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            callListener(result.booleanValue());
            super.onPostExecute(result);
        }

    }

    private void callListener(boolean success) {
        if (mLoadingListener == null)
            return;
        if (success)
            mLoadingListener.onLoadFinished(mReturnData);
        else
            mLoadingListener.onLoadError(mReturnData, mErrorMessage);
    }

    protected void setDataObject(T data) {
        mReturnData = data;
    }

}
